package personal.jinhui.paprika.providers;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import personal.jinhui.paprika.utils.MessageText;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class MessagesHelper {
	private Context mContext;

	public MessagesHelper(Context context) {
		mContext = context;
	}

	public void addMessage(String account, String timestamp, String _from,
			String _to, String msgbody, int iserror) {
		ContentValues values = new ContentValues();
		values.put(UserDataMeta.MessagesTable.ACCOUNT, account);
		values.put(UserDataMeta.MessagesTable.TIMESTAMP, timestamp);
		values.put(UserDataMeta.MessagesTable._FROM, _from);
		values.put(UserDataMeta.MessagesTable._TO, _to);
		values.put(UserDataMeta.MessagesTable.MSGBODY, msgbody);
		values.put(UserDataMeta.MessagesTable.ISERROR, iserror);
		mContext.getContentResolver().insert(
				UserDataMeta.MessagesTable.CONTENT_URI, values);
	}

	public List<MessageText> getMessages(String account) {
		List<MessageText> result = new ArrayList<MessageText>();
		Cursor c = mContext.getContentResolver().query(
				UserDataMeta.MessagesTable.CONTENT_URI, null,
				UserDataMeta.MessagesTable.ACCOUNT + "=?",
				new String[] { account }, null);

		while (c.moveToNext()) {
			String bareJid = null;
			String author = null;
			String _from = c.getString(c
					.getColumnIndex(UserDataMeta.MessagesTable._FROM));
			if(_from == null){
				bareJid = "";
				author = account;
			}else{
				bareJid = _from;
			}

			String msgbody = c.getString(c
					.getColumnIndex(UserDataMeta.MessagesTable.MSGBODY));
			int iserror = c.getInt(c
					.getColumnIndex(UserDataMeta.MessagesTable.ISERROR));
			String timestamp = c.getString(c
					.getColumnIndex(UserDataMeta.MessagesTable.TIMESTAMP));
			boolean _iserror = iserror == 0 ? false : true;
			DateFormat f = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH);
			Date _timestamp = null;
			try {
				_timestamp = f.parse(timestamp);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			MessageText m = new MessageText(bareJid, author, msgbody, _iserror, _timestamp);
			result.add(m);
		}
		return result;
	}
}
